$(function() {
    
    $("#register_form").validate();
        
    $.validator.addMethod('username', function (value, element) {
      return this.optional(element) || /^[a-z][a-z0-9_]+$/i.test(value); 
    }, gettext('username should starts with letters, and only contains letters, digits and underscore'));
    // I avoid using "remote" method since the web services should behave
    // uniformly
    $.validator.addMethod('inexist_username', function (value, element) {
        if (this.optional(element)) {
          return true;
        }
        var req = $.ajax({
          async: false,
          dataType: "json",
          url: '/accounts/api/user_exists',
          data: {'username': value}
        });
        if (req.status == 200) {
          return false;
        }
        return true;
      }, gettext("username already used"));

    $("#id_email").rules('add', 
      {
        required: true, 
        email: true,
        messages: {
          required: gettext('required'),
          email: gettext('invalid email address'),
        }
      });
    $('#id_username').rules('add',
      {
        required: true,
        rangelength: [4, 16],
        username: true,  
        inexist_username: true,
        messages: {
          required: gettext('required'),
          rangelength: gettext("length of username should between 4 and 16"),
        }
      });
    $('#id_password').addClass('password').rules('add', 
      { 
        required: true,
      });
    $.validator.passwordRating.messages = {
        "similar-to-username": gettext("simlilar to username"),
        "too-short": gettext("too short"),
        "very-weak": gettext("very weak"),
        "weak": gettext('weak'),
        "good": gettext('good'),
        "strong": gettext('strong'),
    };
  }
);

